package com.hkunderground.blog.viewer;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.hkunderground.blog.helper.ConstantHelper;

public class ViewByTagServlet extends HttpServlet 
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	  public void doGet(HttpServletRequest req, HttpServletResponse resp)  throws IOException
	   { 
		   this.doPost(req, resp);
	   }//doGet


	  public void doPost(HttpServletRequest req, HttpServletResponse resp)  throws IOException
	  {
		  String lsPathInfo = req.getPathInfo();
		  
		  String[] lsPathInfoArr = lsPathInfo.split("/");
		  
		  //get thr last item
		  String lsTag = lsPathInfoArr[lsPathInfoArr.length-1];
		  
		  DatastoreService loDatastore = DatastoreServiceFactory.getDatastoreService(); 	
		  
		  //tag 
      //	Key loTagKey = KeyFactory.createKey(ConstantHelper.KEY_KIND_TAG, ConstantHelper.KEY_NAME_TAG);
     	    Query loTagQuery = new Query(ConstantHelper.ENTITY_TAG);
 	    	
 	    	loTagQuery.addFilter(ConstantHelper.E_TAG_UPPER_NAME, Query.FilterOperator.EQUAL, lsTag.toUpperCase());
 	    	PreparedQuery lpgTagQuery = loDatastore.prepare(loTagQuery);
 	    	
 	    	Entity loTag = lpgTagQuery.asSingleEntity();
		  
 	    	Query lqBlogTagRel = new Query(ConstantHelper.ENTITY_BLOGTAG_REL);
 	    	lqBlogTagRel.addFilter(ConstantHelper.E_TAG_NAME,  Query.FilterOperator.EQUAL, loTag.getKey());
  	    
 	    	
		  Key lkBlog = KeyFactory.createKey(ConstantHelper.KEY_KIND_BLOG, ConstantHelper.KEY_NAME_BLOG_HKUG);
		  // Run an ancestor query to ensure we see the most up-to-date
		  // view of the Greetings belonging to the selected Guestbook.
		//  Query lqBlog = new Query(ConstantHelper.ENTITY_BLOG, lkBlog).addFilter(propertyName, operator, value) ..addSort(ConstantHelper.E_BLOG_DATE, Query.SortDirection.DESCENDING);
		  //  List<Entity> loBlogList = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
		    

	  }//doPost
}